package com.thinkgem.jeesite.modules.app.api;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.app.entity.A_article;
import com.thinkgem.jeesite.modules.app.entity.AppResultEntity;
import com.thinkgem.jeesite.modules.app.until.WeatherReportByCity;
import com.thinkgem.jeesite.modules.cms.dao.ArticleDao;
import com.thinkgem.jeesite.modules.cms.dao.ArticleDataDao;
import com.thinkgem.jeesite.modules.cms.dao.CategoryDao;
import com.thinkgem.jeesite.modules.cms.entity.*;
import com.thinkgem.jeesite.modules.cms.service.*;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm;
import com.thinkgem.jeesite.modules.sys.security.UsernamePasswordToken;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.thinkgem.jeesite.common.utils.StringUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 开发者 on 16/5/12.
 */
@Controller
@RequestMapping(value = "${adminPath}/api/news")
public class NewsApi extends BaseController{

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleDataService articleDataService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private ExImageService imageService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private WeathersService weathersService;

    @Autowired
    private ExVideoService videoService;

    @Autowired
    private CommentService commentService;

    // 文件保存目录相对路径
    private String basePath = "userfiles/1/images/photo/";

    private String basePathPhoto = "/klmy_news/userfiles/1/images/photo/";

    private String base = "userfiles/";

    private String baseUrl = "/klmy_news/userfiles/";

    private String basePaths = "/images/photo/";

    private String baseBusinessPaths = "/images/cms/cmsBusiness/";

    private Date date = new Date();
    private SimpleDateFormat matter1 = new SimpleDateFormat("yyyy");
    private SimpleDateFormat matter2 = new SimpleDateFormat("MM");

    /*
    获取新闻分类
     */
//    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "getNewsCategory")
    public AppResultEntity getNewsCategory(){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
//        List<Category> datas = categoryService.findByUser();
        List<Category> datas =  categoryService.getCategoryByParanId("3");
//        Category category1 = new Category();
//        category1.setId("0");
//        category1.setParent(category1);
//        category1.setName("头条");
        Map<String, Object> map1 = Maps.newHashMap();
        map1.put("id", "0");
        map1.put("pId", "0");
        map1.put("name", "头条");
        mapList.add(map1);
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", category.getId());
            map.put("pId", category.getParent().getId());
            map.put("name", category.getName());
            mapList.add(map);
        }

        result.setData(mapList);
        return result;
    }

    /**
     * 获取视屏所有分类
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getVideoCategory")
    public AppResultEntity getVideoCategory(){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
//        List<Category> datas = categoryService.findByUser();
        List<Category> datas =  categoryService.getCategoryByParanId("2");
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", category.getId());
            map.put("pId", category.getParent().getId());
            map.put("name", category.getName());
            mapList.add(map);
        }
        result.setData(mapList);
        return result;
    }

    /**
     * 获取图片所有分类
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getImageCategory")
    public AppResultEntity getImageCategory(){
        List<Map<String, Object>> mapList = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
//        List<Category> datas = categoryService.findByUser();
        List<Category> datas =  categoryService.getCategoryByParanId("4");
        for(Category category : datas)
        {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", category.getId());
            map.put("pId", category.getParent().getId());
            map.put("name", category.getName());
            mapList.add(map);
        }
        result.setData(mapList);
        return result;
    }
/*
按新闻分类id获取新闻
 */
//    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "getNewsByCategoryId")
    public AppResultEntity getNewsByCategoryId(Article article, HttpServletRequest request, HttpServletResponse response, Model model){
        article.setDelFlag(Article.DEL_FLAG_NORMAL);
        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true);
        List<A_article> results = Lists.newArrayList();
        ArticleData articleData = new ArticleData();
        for(Article article1 : page.getList()) {
            A_article aArticle = new A_article(article1);
            aArticle.setUrl("/f/view-" + article1.getCategory().getId() + "-" + article1.getId() + ".html");
            aArticle.setCommentCount(commentService.findArticleCommentCountsByArticleId(article1.getId()));
            aArticle.setId(article1.getId());
            results.add(aArticle);
            }

        AppResultEntity result = new AppResultEntity();
        if(results.size() != 0 ){
            result.setData(results);
        }

        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "getTopNews")
    public AppResultEntity getTopNews(Article article, HttpServletRequest request, HttpServletResponse response, Model model){
        AppResultEntity result = new AppResultEntity();
        article.setDelFlag(Article.DEL_FLAG_NORMAL);
        article.setPosid("3");
        List<A_article> results = Lists.newArrayList();
        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true);
        for(Article article1 : page.getList()) {
            A_article aArticle = new A_article(article1);
            aArticle.setUrl("/f/view-" + article1.getCategory().getId() + "-" + article1.getId() + ".html");
            aArticle.setCommentCount(commentService.findArticleCommentCountsByArticleId(article1.getId()));
            aArticle.setId(article1.getId());
            results.add(aArticle);
        }
        if(results.size() != 0 ){
            result.setData(results);
        }

        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return result;

    }

    /**
     * 按分类id获取视屏
     * @param cateGoryId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getVideoByCategoryId")
    public AppResultEntity getVideoByCategoryId(String cateGoryId){
//        Page<ExVideo> page = videoService.findPage(new Page<ExVideo>(request, response), article);
//        videoService.findPage()
        AppResultEntity result = new AppResultEntity();
        List<ExVideo> list = Lists.newArrayList();
        list = videoService.getVideoByCategoryId(cateGoryId);
        result.setData(list);
//        result.setPage(page.getPageNo());
//        result.setPageSize(page.getPageSize());
        return result;
    }

    /**
     * 按分类id获取图片新闻
     * @param cateGoryId
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "getImgByCategoryId")
    public AppResultEntity getImgByCategoryId(String cateGoryId){
//        Page<ExVideo> page = videoService.findPage(new Page<ExVideo>(request, response), article);
//        videoService.findPage()
        AppResultEntity result = new AppResultEntity();
        List<ExImage> list = Lists.newArrayList();
        list = imageService.getImgByCategoryId(cateGoryId);
        result.setData(list);
//        result.setPage(page.getPageNo());
//        result.setPageSize(page.getPageSize());
        return result;
    }

    /*
    轮播新闻
     */
//    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "getTurnNewsByCategoryId")
    public AppResultEntity getNewsCategoryId( HttpServletRequest request, HttpServletResponse response){
//        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true);
//        List<A_article> results = Lists.newArrayList();
        AppResultEntity result = new AppResultEntity();
        String a = request.getParameter("category.id");

        List<Article> list = articleService.getTurnNewsById(a);
        List<A_article> aArticlesList = Lists.newArrayList();

        Category category = categoryService.get(a);
            for(Article article : list){
                ArticleData articleData = new ArticleData();
                articleData = articleDataService.getArticleDataById(article.getId());
                A_article aArticle = new A_article(article);
                aArticle.setUrl("/f/view-" + aArticle.getCategory().getId() + "-" + aArticle.getId() + ".html");
                if(aArticlesList.size() < 4) {
                    aArticlesList.add(aArticle);
                }else{
                    break;
                }
            }
        if(aArticlesList.size() != 0){
            result.setData(aArticlesList);
        }

        return result;

    }

    @ResponseBody
    @RequestMapping(value = "getNewsImage")
    public AppResultEntity getNewsImage(ExImage image, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        image.setDelFlag(ExImage.DEL_FLAG_NORMAL);
        Page<ExImage> page = imageService.findPage(new Page<ExImage>(request, response), image);
        result.setData(page.getList());
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "getTurnNewsImage")
    public AppResultEntity getTurnNewsImage(ExImage image, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        image.setDelFlag(ExImage.DEL_FLAG_NORMAL);
        Page<ExImage> page = imageService.findPage(new Page<ExImage>(request, response), image);
        List<ExImage> list = new ArrayList<ExImage>();
        for(ExImage exImage : page.getList()){
            if(list.size() < 4){
                list.add(exImage);
            }
        }
        result.setData(list);
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "getNewsVideo")
    public AppResultEntity getNewsVideo(ExVideo video, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        video.setDelFlag(ExVideo.DEL_FLAG_NORMAL);
        Page<ExVideo> page = videoService.findPage(new Page<ExVideo>(request, response), video);
        result.setData(page.getList());
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return result;
    }

    /**
     * 获取视屏轮播
     * @param video
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getTurnNewsVideo")
    public AppResultEntity getTurnNewsVideo(ExVideo video, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        video.setDelFlag(ExVideo.DEL_FLAG_NORMAL);
        Page<ExVideo> page = videoService.findPage(new Page<ExVideo>(request, response), video);
        List<ExVideo> list = new ArrayList<ExVideo>();
        for(ExVideo exVideo : page.getList()){
            if(list.size() < 4){
                list.add(exVideo);
            }
        }
        result.setData(list);
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return result;
    }

    /**
     * 按视屏分类返回视屏数据
     * @param video
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNewsVideoCategory")
    public AppResultEntity getNewsVideoCategory(ExVideo video, HttpServletRequest request, HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        video.setDelFlag(ExVideo.DEL_FLAG_NORMAL);
        Page<ExVideo> page = videoService.findPage(new Page<ExVideo>(request, response), video);
        List<Map<String,List<ExVideo>>> reList = new ArrayList<Map<String, List<ExVideo>>>();
        Map<String,List<ExVideo>> map = new HashMap<String, List<ExVideo>>();
        for(ExVideo exVideo : page.getList()){
            List<ExVideo> list = new ArrayList<ExVideo>();
            Category category = categoryService.get(exVideo.getCategory().getId());
            String id = category.getName();
            if(map.get(id) == null ){
                list.add(exVideo);
                map.put(id,list);
            }else if(map.get(id).size() <= 4){
                list = map.get(id);
                list.add(exVideo);
                map.put(id,list);
            }

          reList.add(map);
        }
        result.setData(reList);
//        result.setData(page.getList());
        result.setPageSize(page.getPageSize());
        result.setPage(page.getPageNo());
        return result;
    }


/*
个人信息接口
 */
//    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "myinfo")
    public AppResultEntity getMyInfo(String userId) {
        AppResultEntity result = new AppResultEntity();
        result.setData(systemService.getUser(userId));
        return result;
    }

    /**
     * 修改个人信息
     * @param user
     * @param response
     * @param request
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "modifyMobileInfo")
//    public AppResultEntity modifyMobileInfo(User user,HttpServletResponse response,HttpServletRequest request){
//        AppResultEntity result = new AppResultEntity();
//        systemService.updateUserInfo();
//        return result;
//    }

    /**
     * 修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "modifypwd")
    public AppResultEntity modifypwd(String id,String oldPassword,String newPassword){
        AppResultEntity result = new AppResultEntity();
        User user = systemService.getUser(id);
        if(StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
            if(SystemService.validatePassword(oldPassword,user.getPassword())){
                systemService.updatePasswordById(user.getId(),user.getLoginName(),newPassword);
            }else {
                result.setErrNo(-1);
                result.setErrMessage("修改密码失败，旧密码错误");
            }
        }
        return result;
    }

    /*
    图片新闻
     */
//    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "getPicOrFlashNewsById")
    public AppResultEntity getPicOrFlashNewsById(Article article, HttpServletRequest request, HttpServletResponse response, Model model){
        Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true);
        List<A_article> results = Lists.newArrayList();
        for(Article article1 : page.getList()){
            A_article aArticle = new A_article(article1);
            aArticle.setArticleData(articleDataService.getArticleDataById(article1.getId()));
            results.add(aArticle);
        }
        AppResultEntity result = new AppResultEntity();
        result.setData(results);
        result.setPage(page.getPageNo());
        result.setPageSize(page.getPageSize());
        return result;
    }

    /**
     * 手机登陆
     * @param request
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "mLogin")
    public AppResultEntity mLogin(HttpServletRequest request) {
        AppResultEntity result = new AppResultEntity();
        String host = request.getRemoteHost();
        String username = request.getParameter("username");
        AuthenticationToken token = new UsernamePasswordToken(username, request.getParameter("password").toCharArray(), true, host ,"",true);
        try {
            Subject subject = SecurityUtils.getSubject();
            ThreadContext.bind(subject);
            if(subject.getPrincipal() != null){
                subject.logout();
            }
            subject.login(token);
            result.setData(systemService.getUserByLoginName(username));
            User user = new User();
        } catch (AuthenticationException e) {
            logger.info("验证失败");
            result.setErrNo(-1);
            result.setErrMessage("认证失败");
        } catch (Exception e) {
            logger.error("登录失败", e);
            result.setErrNo(-2);
            result.setErrMessage("登录失败");
        }
        return result;
    }

    /**
     * 注册接口
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "register")
    public Object register(User user,HttpServletRequest request){
        AppResultEntity result = new AppResultEntity();
        Role role = new Role();
        List<Role> roleLists = new ArrayList<Role>();
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Iterator<String> names =  multipartRequest.getFileNames();
//        String path = request.getRealPath("/") + basePath;
//
//        String url = "";
//        while (names.hasNext()) {
//            String s = UUID.randomUUID().toString();
//            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
//            String name = names.next();
//            MultipartFile file = multipartRequest.getFile(name);
//            File saveFile = new File(path,s + ".png");
//            File pathFile = new File(path);
//            if(!pathFile.exists()){
//                pathFile.mkdir();
//            }
//            url = basePath + s +  ".png";
//            try {
//                file.transferTo(saveFile);
////                urls += (url + ",");
//            } catch (IOException e) {
//                e.printStackTrace();
//                result.setErrNo(-1);
//                result.setErrMessage(e.getMessage());
//            }
//        }
//        if(url.length()>0) {
////            String dataUrl = urls.substring(0, urls.length() - 1);
////            data.setDataUrl(url);
//            user.setPhoto(url);
//        }
        role.setId("6");
        roleLists.add(role);
        user.setRoleList(roleLists);
        user.setUserType("3");
        user.setPassword(SystemService.entryptPassword(user.getPassword()));
        user.setCreateBy(systemService.getUser("1"));
        user.setUpdateBy(systemService.getUser("1"));
        user.setCompany(officeService.get("1"));
        user.setOffice(officeService.get("85ea3fde626c4e7ca802e5ae4a42ffee"));
        // 如果新密码为空，则不更换密码
//        if (StringUtils.isNotBlank(user.getNewPassword())) {
//            user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
//        }
        if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
            result.setErrNo(-2);
            result.setErrMessage("用户名已存在");
            return result;
        }
        // 保存用户信息
        systemService.saveUser(user);
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            UserUtils.clearCache();
            //UserUtils.getCacheMap().clear();
        }
        if((user.getLoginName() == null || user.getLoginName().equals("")) || (user.getPassword() == null || user.getPassword() .equals("")) ||
                (user.getName() == null || user.getName().equals(""))){
            result.setErrNo(-1);
            result.setErrMessage("账号、密码、姓名不能为空");
            return result;
        }

        return result;
    }


    /**
     * 更换头像
     * @param user
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updatePhoto")
    public Object updatePhoto(User user,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        response.setHeader("Access-Control-Allow-Origin", "*");
//        User user = new User();
        List<Object> list = new ArrayList<Object>();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<String> names =  multipartRequest.getFileNames();
        String path = request.getRealPath("/") + base + user.getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/";
        System.out.print(path);

        String url = "";
        while (names.hasNext()) {
            String s = UUID.randomUUID().toString();
            s =  s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
            String name = names.next();
            MultipartFile file = multipartRequest.getFile(name);
            File saveFile = new File(path,s + ".png");
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            url = baseUrl + user.getId() + basePaths + matter1.format(date) + "/" + matter2.format(date) + "/" + s +  ".png";
            try {
                file.transferTo(saveFile);
//                urls += (url + ",");
            } catch (IOException e) {
                e.printStackTrace();
                result.setErrNo(-1);
                result.setErrMessage(e.getMessage());
            }
        }

        user = systemService.getUser(user.getId());
        if(url.length()>0) {
            user.setPhoto(url);
        }
        user.setUpdateBy(user);
        user.setUpdateDate(new Date());
        systemService.updateUserInfo(user);
        result.setData(url);
        return result;

    }

    /**
     * 获取评论
     * @param article
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getComment")
    public Object getComment(Article article,HttpServletRequest request,HttpServletResponse response){
        AppResultEntity result = new AppResultEntity();
        List<A_article> list = new ArrayList<A_article>();
        Page<Article> page = articleService.findsPage(new Page<Article>(request, response), article);
        for(Article article1:page.getList()){
            A_article aArticle = new A_article(article1);
            aArticle.setUrl("/f/view-" + article1.getCategory().getId() + "-" + article1.getId() + ".html");
            aArticle.setCommentCount(commentService.findArticleCommentCountsByArticleId(article1.getId()));
            list.add(aArticle);
        }
        result.setData(list);
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "weatherAndVegetable")
    public Weathers weather(){
//        return WeatherReportByCity.GetTodayTemperatureByCity("克拉玛依");

        return weathersService.getWeather();
    }

    public static void main(String[] args) throws IOException {

//    	 System.out.println(WeatherReportByCity.GetTodayTemperatureByCity("克拉玛依"));
        System.out.print(parseBeanFromJson());


    }

    public static Object parseBeanFromJson() throws IOException{
        String a = WeatherReportByCity.GetTodayTemperatureByCity("克拉玛依");
        System.out.print(a);
        return null;
    }

    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName !=null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }
}
